package google.data;

import google.data.DataItem;
import google.data.EMF;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class Data {
	public void createData(String key, String value) {
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		DataItem dataItem = new DataItem(key, value);
		try {
			tx.begin();
			em.persist(dataItem);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
	}

	public String readValue(String key) {
		EntityManager em = EMF.get().createEntityManager();
		if(em.find(DataItem.class, key).getValue()==null)
			return "No Data Found";
		return em.find(DataItem.class, key).getValue();
	}
	
	public List<DataItem> readAllValue() {
		EntityManager em = EMF.get().createEntityManager();
		List<DataItem> resultList = new ArrayList<DataItem>(em.createQuery("select t from DataItem t").getResultList()) ;
//		List<DataItem> resultList = new ArrayList<DataItem>() ;
//		resultList.add(new DataItem("121","rahul"));
		return resultList;
	}

	public void updateValue(String key, String value) {
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		DataItem dataItem = em.find(DataItem.class, key);
		dataItem.setValue(value);
		try {
			tx.begin();
			em.merge(dataItem);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
	}

	public void deleteData(String key) {
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		DataItem dataItem = em.find(DataItem.class, key);
		try {
			tx.begin();
			em.remove(dataItem);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
	}
}
